package com.fxsh168.server.services;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.fxsh168.server.entitys.NewSound;
import com.fxsh168.server.entitys.SoundsToken;
import com.fxsh168.server.interfaces.Constant;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import okhttp3.Call;


public class VoiceSynthesisService extends Service {
    private static String token = "";
    private static final String apiKey = Constant.APIKEY;
    private static final String secretKey = Constant.SECRETKEY;
    private static String cuid = "";
    private static final String lan = "zh";
    private static String tex = "";//
    private static String upTe = "";//
    String voice_down, voice_up;

    public VoiceSynthesisService() throws Exception {

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        getSound();
    }


    //   获取语音文本
    public void getSound() {
        OkHttpUtils.get().url(Constant.USERYUYIN).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                Log.e("tag", "语音接口获取，新" + response);
                NewSound newSound = new Gson().fromJson(response, NewSound.class);
                if (newSound.getCode().equals(200 + "")) {
                    voice_down = newSound.getData().get(0).getVoice_down();
                    voice_up = newSound.getData().get(0).getVoice_aboard();
                    cuid = getIMEI();
                    tex = voice_down;
                    upTe = voice_up;
                    getToken();
                }
            }
        });

    }

    public String getIMEI() {
        TelephonyManager mTm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        String imei = mTm.getDeviceId();
        return imei;
    }

    //             获取Token
    private void getToken() {
        String getTokenURL = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials" +
                "&client_id=" + apiKey + "&client_secret=" + secretKey;
        OkHttpUtils.get().url(getTokenURL).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e("tag", "获取token失败" + e);
            }

            @Override
            public void onResponse(String response, int id) {
                PrintWriter output = null;
                if (response != null) {
                    SoundsToken soundsToken = new Gson().fromJson(response, SoundsToken.class);
                    token = soundsToken.getAccess_token();
                    try {
                        method1();
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    Log.e("tag", "与验证服务器验证  获取token" + token);
                }
            }
        });
    }

    //     获取语音文件
    private void method1() throws UnsupportedEncodingException {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpUtils.get().url("http://tsn.baidu.com/text2audio?tex=" + URLEncoder.encode(URLEncoder.encode(tex, "UTF-8"), "UTF-8") + "&lan=zh&cuid=9497197&ctp=1&tok=" + token)
                            .build().execute(new FileCallBack(Environment.getExternalStorageDirectory() + "/sound", "down.mp3") {
                        @Override
                        public void onError(Call call, Exception e, int id) {

                        }

                        @Override
                        public void onResponse(File response, int id) {

                        }
                    });
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }).start();


        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpUtils.get().url("http://tsn.baidu.com/text2audio?tex=" + URLEncoder.encode(URLEncoder.encode(upTe, "UTF-8"), "UTF-8") + "&lan=zh&cuid=9497197&ctp=1&tok=" + token)
                            .build().execute(new FileCallBack(Environment.getExternalStorageDirectory() + "/sound", "up.mp3") {
                        @Override
                        public void onError(Call call, Exception e, int id) {

                        }

                        @Override
                        public void onResponse(File response, int id) {

                        }
                    });
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }).start();


        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpUtils.get().url("http://tsn.baidu.com/text2audio?tex=" + URLEncoder.encode(URLEncoder.encode("您有一个新订单", "UTF-8"), "UTF-8") + "&lan=zh&cuid=9497197&ctp=1&tok=" + token)
                            .build().execute(new FileCallBack(Environment.getExternalStorageDirectory() + "/sound", "new.mp3") {
                        @Override
                        public void onError(Call call, Exception e, int id) {

                        }

                        @Override
                        public void onResponse(File response, int id) {

                        }
                    });
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
}
